package org.gao.gift.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import org.apache.commons.lang.StringUtils;
import org.gao.gift.domain.User;
import org.gao.gift.dto.UserRegisterDto;
import org.gao.gift.mapper.UserMapper;
import org.gao.gift.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.gao.gift.util.BitStatesUtils;
import org.gao.gift.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author yaohuaipeng
 * @since 2024-09-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    /*
        1.做参数的校验  [非空,格式]
        2.验证手机验证码是否正确
        3.准备封装保存的对象
            User
            认证中心 LoginUser
        4.保存数据
            4.1 发起远程调用  -->先保存认证中心数据 -->返回主键id
            4.2 保存本地数据  -->完成数据的填充

     */
    @Override
    public void register(UserRegisterDto dto) {
        // 进行数据校验
        checkData(dto);
        // 数据封装
        User user = userBean(dto);

        // 发起远程调用
    }

    private User userBean(UserRegisterDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        user.setPassword(DigestUtil.md5Hex(salt+dto.getPassword()));
        user.setCreateTime(new Date().getTime());
        long l = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        long state = BitStatesUtils.addState(l, BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(state);
        return user;
    }

    private void checkData(UserRegisterDto dto) {
        //1.验证手机号非空,并且是一个手机号
        if (StringUtils.isBlank(dto.getPhone())) {
            throw new RuntimeException("手机号不能为空");
        }
        //2.验证手机号是个手机号
        if (!dto.getPhone().matches("^1[3-9]\\\\d{9}$")) {
            throw new RuntimeException("手机号格式不正确");

        }
        if (StringUtils.isBlank(dto.getPhoneCode())) {
            throw new RuntimeException("验证码不能为空");
        }
        if (StringUtils.isBlank(dto.getPassword())) {
            throw new RuntimeException("密码不能为空");
        }

        String key = dto.getType()+":"+dto.getPhone();
        // 验证码的正确性校验
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null){
            throw new RuntimeException("验证码不正确");
        }
        if (!o.toString().split(":")[0].equals(dto.getPhoneCode())) {
            throw new RuntimeException("验证码不正确");
        }


    }
}
